package com.bdqn.service;

import com.bdqn.base.R;
import com.bdqn.feign.FeignAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * AuthGlobalFilter
 *
 * @author LILIBO
 * @since 2023-03-14
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private FeignAuthService feignAuthService;

    /**
     * 全局过滤器
     *
     * @param exchange 交换机
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("token");
        log.info("进入自定义的全局过滤器 MyGlobalFilter Token: " + token);
        // 对获取Token接口放行
        String uri = exchange.getRequest().getURI().getPath();
        log.info("进入自定义的全局过滤器 MyGlobalFilter URI: " + uri);
        if (uri.startsWith("/auth")) {
            // 交给下一个过滤器链
            return chain.filter(exchange);
        }

        if (StringUtils.isEmpty(token)) {
            // 远程调用认证模块，验证Token合法性
            R verify = feignAuthService.verify(token);
            if (verify.getCode() != 0 || !Boolean.valueOf(verify.getData().toString())) {
                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
                return exchange.getResponse().setComplete(); // 返回结果
            }
        }
        // 交给下一个过滤器链
        return chain.filter(exchange);
    }

    /**
     * 过滤器的顺序，0表示第一个
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
